import sys

from PySide6.QtCore import QSize, Qt, QCoreApplication, QPropertyAnimation
from PySide6.QtGui import QIcon, QPixmap, QCursor, QFontDatabase
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QSpacerItem, QSizePolicy, QLabel, QLineEdit,
    QListWidget, QSlider, QFrame, QListWidgetItem, QSplitter, QAbstractItemView
)

# 确保 resource_rc.py 文件可以被正确导入
try:
    from resource_rc import *
except ImportError:
    print("资源文件 resource_rc.py 未找到，请确保已正确生成。")
    sys.exit(1)


class MainWindowUI:
    """
    手动实现的UI类，替代由 .ui 文件生成的 Ui_MainWindow。
    这个类负责创建和布局所有UI组件。
    """

    def setupUi(self, MainWindow: QMainWindow):
        """设置主窗口UI"""
        if not MainWindow.objectName():
            MainWindow.setObjectName("MainWindow")
        MainWindow.resize(750, 380)
        icon = QIcon(":/images/images/music.png")
        MainWindow.setWindowIcon(icon)
        MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", "LrcMusicPlayer", None))

        # 从外部文件加载QSS样式
        try:
            with open('style.qss', 'r', encoding='utf-8') as f:
                style_sheet = f.read()
            MainWindow.setStyleSheet(style_sheet)
        except FileNotFoundError:
            print("警告: 未找到样式文件 'style.qss'，将使用默认样式。")

        # 创建中央控件和主布局
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        main_layout = QHBoxLayout(self.centralwidget)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(5, 5, 5, 5)

        # 创建主内容区域
        self.widget = QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.widget.setFocusPolicy(Qt.FocusPolicy.StrongFocus)

        content_layout = QVBoxLayout(self.widget)
        content_layout.setSpacing(0)
        content_layout.setContentsMargins(0, 0, 0, 0)

        # 添加顶部、中部和底部控件
        self._create_top_bar(content_layout)
        self._create_body_panel(content_layout)
        self._create_bottom_bar(content_layout)

        main_layout.addWidget(self.widget)
        MainWindow.setCentralWidget(self.centralwidget)

    def _create_top_bar(self, parent_layout):
        """创建顶部栏"""
        self.widget_top = QWidget()
        self.widget_top.setObjectName("widget_top")
        self.widget_top.setMinimumSize(QSize(0, 28))
        self.widget_top.setMaximumSize(QSize(16777215, 28))
        top_layout = QHBoxLayout(self.widget_top)
        top_layout.setSpacing(7)
        top_layout.setContentsMargins(10, 0, 10, 0)

        # 红绿灯按钮
        lights_layout = QHBoxLayout()
        lights_layout.setSpacing(6)

        self.pushButton_red = QPushButton()
        self.pushButton_red.setObjectName("pushButton_red")
        self.pushButton_red.setFixedSize(12, 12)
        self.pushButton_red.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_red.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        self.pushButton_yellow = QPushButton()
        self.pushButton_yellow.setObjectName("pushButton_yellow")
        self.pushButton_yellow.setFixedSize(12, 12)
        self.pushButton_yellow.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_yellow.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        self.pushButton_green = QPushButton()
        self.pushButton_green.setObjectName("pushButton_green")
        self.pushButton_green.setFixedSize(12, 12)
        self.pushButton_green.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_green.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        lights_layout.addWidget(self.pushButton_red)
        lights_layout.addWidget(self.pushButton_yellow)
        lights_layout.addWidget(self.pushButton_green)
        top_layout.addLayout(lights_layout)

        top_layout.addSpacerItem(QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum))

        # 版本更新按钮
        self.pushButton_update = QPushButton("v0.0.0")
        self.pushButton_update.setObjectName("pushButton_update")
        self.pushButton_update.setMinimumSize(QSize(50, 0))
        self.pushButton_update.setMaximumSize(QSize(50, 16777215))
        self.pushButton_update.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_update.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        top_layout.addWidget(self.pushButton_update)

        parent_layout.addWidget(self.widget_top)

    def _create_body_panel(self, parent_layout):
        """创建主内容区域（使用QSplitter实现可拖动调整大小）"""
        # 创建一个水平方向的QSplitter
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setHandleWidth(3)  # 设置拖动条的宽度
        splitter.setContentsMargins(10, 10, 10, 10) # 保持原有的边距

        # 创建并添加各个面板
        music_list_widget = self._create_music_list_panel()
        lrc_widget = self._create_lrc_panel()
        info_widget = self._create_info_panel()
        comment_widget = self._create_comment_panel()

        splitter.addWidget(music_list_widget)
        splitter.addWidget(lrc_widget)
        splitter.addWidget(info_widget)
        splitter.addWidget(comment_widget)

        # 设置初始的拉伸因子，保持原来的比例
        splitter.setStretchFactor(0, 2)
        splitter.setStretchFactor(1, 4)
        splitter.setStretchFactor(2, 2)
        splitter.setStretchFactor(3, 2)

        # 将splitter添加到父布局中
        parent_layout.addWidget(splitter)

    def _create_music_list_panel(self):
        """创建左侧音乐列表面板"""
        panel_widget = QWidget()  # 创建一个容器Widget
        layout = QVBoxLayout(panel_widget)  # 将布局设置给这个Widget
        layout.setSpacing(4)
        layout.setContentsMargins(0, 0, 0, 0)

        save_btn_layout = QHBoxLayout()
        self.label_list_name = QLabel("歌曲列表")
        self.label_list_name.setObjectName("label_list_name")
        self.pushButton_save_to_playlist = QPushButton("Save")
        self.pushButton_save_to_playlist.setObjectName("pushButton_save_to_playlist")
        self.pushButton_save_to_playlist.setFixedSize(40, 15)
        self.pushButton_save_to_playlist.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_save_to_playlist.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        save_btn_layout.addWidget(self.label_list_name, 8)
        save_btn_layout.addWidget(self.pushButton_save_to_playlist, 4)
        layout.addLayout(save_btn_layout)

        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText("搜索")
        self.lineEdit.setMaximumHeight(20)
        self.lineEdit.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
        layout.addWidget(self.lineEdit)

        self.listWidget = QListWidget()
        self.listWidget.setObjectName("listWidget")
        self.listWidget.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) # 平滑滚动
        self.listWidget.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.listWidget.setFrameShape(QFrame.Shape.NoFrame)
        self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        layout.addWidget(self.listWidget)

        self.pushButton_song_find = QPushButton()
        self.pushButton_song_find.setObjectName("pushButton_song_find")
        self.pushButton_song_find.setMaximumHeight(15)
        self.pushButton_song_find.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_song_find.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.pushButton_song_find.setFlat(True)
        layout.addWidget(self.pushButton_song_find)

        layout.setStretch(0, 1)
        layout.setStretch(1, 1)
        layout.setStretch(2, 10)
        layout.setStretch(3, 1)
        return panel_widget  # 返回容器Widget

    def _create_lrc_panel(self):
        """创建中央歌词面板"""
        panel_widget = QWidget()  # 创建一个容器Widget
        layout = QVBoxLayout(panel_widget)  # 将布局设置给这个Widget
        layout.setContentsMargins(5, 5, 5, 5)
        layout.setSpacing(0)

        # 歌曲标题标签
        self.label_name = QLabel("Title")
        self.label_name.setObjectName("label_name")
        self.label_name.setAlignment(Qt.AlignmentFlag.AlignLeft)
        layout.addWidget(self.label_name)

        # 歌词列表
        self.listWidget_2 = QListWidget()
        self.listWidget_2.setObjectName("listWidget_2")
        self.listWidget_2.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.listWidget_2.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.listWidget_2.setFrameShape(QFrame.Shape.NoFrame)
        self.listWidget_2.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.listWidget_2.setSpacing(2)  # 设置项目间距

        # 欢迎文本
        for _ in range(2):
            item = QListWidgetItem("", self.listWidget_2)
            item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsSelectable)
        item1 = QListWidgetItem("LrcMusicPlayer by Nagisa", self.listWidget_2)
        item1.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        item1.setFlags(item1.flags() & ~Qt.ItemFlag.ItemIsSelectable)  # 使欢迎文本不可选中
        item2 = QListWidgetItem("2021.11.6", self.listWidget_2)
        item2.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        item2.setFlags(item2.flags() & ~Qt.ItemFlag.ItemIsSelectable)
        for _ in range(2):
            item = QListWidgetItem("", self.listWidget_2)
            item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsSelectable)

        layout.addWidget(self.listWidget_2)
        return panel_widget

    def _create_info_panel(self):
        """创建右侧信息面板"""
        self.widget_info = QWidget()
        layout = QVBoxLayout(self.widget_info)
        layout.setSpacing(2)
        layout.setContentsMargins(0, 0, 0, 0)

        pic_layout = QHBoxLayout()
        pic_layout.setContentsMargins(5, 5, 5, 5)
        self.widget_pic = QWidget()
        self.widget_pic.setFixedSize(150, 150)
        self.label_pic = QLabel(self.widget_pic)
        self.label_pic.setGeometry(0, 0, 150, 150)
        self.label_pic.setPixmap(QPixmap(":/images/images/Nagisa.png"))
        self.label_pic.setScaledContents(True)
        self.label_pic_hires = QLabel(self.widget_pic)
        self.label_pic_hires.setGeometry(5, 125, 20, 20)
        self.label_pic_hires.setPixmap(QPixmap(":/images/images/hi-res.jpg"))
        self.label_pic_hires.setScaledContents(True)
        pic_layout.addWidget(self.widget_pic)
        layout.addLayout(pic_layout)

        self.label_info = QLabel("MUSIC INFO")
        self.label_info.setObjectName("label_info")
        self.label_info.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.label_info)

        info_list_layout = QHBoxLayout()
        info_list_layout.setSpacing(0)
        self.listWidget_3 = QListWidget()
        self.listWidget_3.setObjectName("listWidget_3")
        self.listWidget_3.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) # 平滑滚动
        self.listWidget_3.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.listWidget_3.setFrameShape(QFrame.Shape.NoFrame)
        self.listWidget_3.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        QListWidgetItem("标题：LrcMusicPlayer", self.listWidget_3)
        QListWidgetItem("作者：Nagisa", self.listWidget_3)
        QListWidgetItem("日期：2021-11-6", self.listWidget_3)
        QListWidgetItem("", self.listWidget_3)
        QListWidgetItem("点击左下角加号载入歌曲~", self.listWidget_3)
        info_list_layout.addWidget(self.listWidget_3, 0, Qt.AlignmentFlag.AlignHCenter)
        layout.addLayout(info_list_layout)

        return self.widget_info

    def _create_comment_panel(self):
        """创建评论面板"""
        self.widget_comment = QWidget()
        layout = QVBoxLayout(self.widget_comment)
        layout.setContentsMargins(0, 0, 0, 0)

        self.label_hot_comment = QLabel("热门评论")
        self.label_hot_comment.setObjectName("label_hot_comment")
        layout.addWidget(self.label_hot_comment)

        self.listWidget_comment = QListWidget()
        self.listWidget_comment.setObjectName("listWidget_comment")
        self.listWidget_comment.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) # 平滑滚动
        self.listWidget_comment.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.listWidget_comment.setFrameShape(QFrame.Shape.NoFrame)
        self.listWidget_comment.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        layout.addWidget(self.listWidget_comment)
        return self.widget_comment

    def _create_bottom_bar(self, parent_layout):
        """创建底部控制栏"""
        self.widget_bottom = QWidget()
        self.widget_bottom.setObjectName("widget_bottom")
        self.widget_bottom.setMinimumHeight(45)
        self.widget_bottom.setMaximumHeight(45)

        bottom_layout = QHBoxLayout(self.widget_bottom)
        bottom_layout.setSpacing(10)
        bottom_layout.setContentsMargins(10, 5, 10, 5)

        left_btn_layout = QHBoxLayout()
        left_btn_layout.setSpacing(8)
        self.pushButton_path = self._create_bottom_button(":/icon/images/folder_add.png", ":/icon/images/folder_add 深色.png")
        self.pushButton_last = self._create_bottom_button(":/icon/images/上一曲.png", ":/icon/images/上一曲 深色.png")
        self.pushButton_start = self._create_bottom_button(":/icon/images/暂停.png", ":/icon/images/暂停 深色.png", QSize(35, 35))
        self.pushButton_next = self._create_bottom_button(":/icon/images/下一曲.png", ":/icon/images/下一曲 深色.png")
        self.pushButton_change_sort_mode = self._create_bottom_button(":/icon/images/排序.png", ":/icon/images/排序 深色.png")

        left_btn_layout.addWidget(self.pushButton_path)
        left_btn_layout.addWidget(self.pushButton_last)
        left_btn_layout.addWidget(self.pushButton_start)
        left_btn_layout.addWidget(self.pushButton_next)
        left_btn_layout.addWidget(self.pushButton_change_sort_mode)
        bottom_layout.addLayout(left_btn_layout)

        self.label_time_start = QLabel("00:00")
        self.label_time_start.setObjectName("label_time_start")
        self.horizontalSlider = QSlider(Qt.Orientation.Horizontal)
        self.horizontalSlider.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.label_time_end = QLabel("00:00")
        self.label_time_end.setObjectName("label_time_end")

        bottom_layout.addWidget(self.label_time_start)
        bottom_layout.addWidget(self.horizontalSlider)
        bottom_layout.addWidget(self.label_time_end)

        right_btn_layout = QHBoxLayout()
        right_btn_layout.setSpacing(8)
        self.pushButton_volume = QPushButton("66")
        self.pushButton_volume.setObjectName("pushButton_volume")
        self.pushButton_volume.setFixedSize(25, 25)
        self.pushButton_volume.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.pushButton_volume.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.pushButton_random = self._create_bottom_button(":/icon/images/列表循环.png", ":/icon/images/列表循环 深色.png")
        self.pushButton_is_trans = self._create_bottom_button(":/icon/images/翻译.png", ":/icon/images/翻译 深色.png")
        self.pushButton_is_online = self._create_bottom_button(":/icon/images/cloud_off.png", ":/icon/images/cloud_off 深色.png")
        self.pushButton_is_comment = self._create_bottom_button(":/icon/images/search.png", ":/icon/images/search 深色.png")

        right_btn_layout.addWidget(self.pushButton_volume)
        right_btn_layout.addWidget(self.pushButton_random)
        right_btn_layout.addWidget(self.pushButton_is_trans)
        right_btn_layout.addWidget(self.pushButton_is_online)
        right_btn_layout.addWidget(self.pushButton_is_comment)
        bottom_layout.addLayout(right_btn_layout)

        parent_layout.addWidget(self.widget_bottom)

    def _create_bottom_button(self, normal_icon, hover_icon, size=QSize(25, 25)):
        """辅助方法：创建底部图标按钮"""
        button = QPushButton()
        button.setFixedSize(size)
        button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        # 注意：这里的样式是动态设置的，保留在代码中是合理的
        button.setStyleSheet(f"""
            QPushButton{{ border:none; image: url({normal_icon}); }}
            QPushButton:hover{{ image: url({hover_icon}); }}
        """)
        button.setFlat(True)
        return button


# --- 用于独立测试UI ---
if __name__ == '__main__':
    app = QApplication(sys.argv)
    font_path = ':/fonts/fonts/LXGWWenKai-Regular.ttf'
    fid = QFontDatabase.addApplicationFont(font_path)

    main_window = QMainWindow()
    ui = MainWindowUI()
    ui.setupUi(main_window)

    main_window.setWindowFlags(Qt.FramelessWindowHint)
    main_window.setAttribute(Qt.WA_TranslucentBackground)

    # 创建窗口淡入动画
    fade_in_animation = QPropertyAnimation(main_window, b"windowOpacity")
    fade_in_animation.setDuration(300)  # 动画持续时间300毫秒
    fade_in_animation.setStartValue(0.0) # 初始透明度为0
    fade_in_animation.setEndValue(1.0)   # 结束透明度为1

    main_window.show()
    fade_in_animation.start() # 启动动画

    sys.exit(app.exec())